package ai.people.netmon.gateway.filter;

import ai.people.netmon.framework.exception.enums.AuthExceptionEnum;
import ai.people.netmon.framework.exception.type.AuthException;
import ai.people.netmon.gateway.properties.GatewayProperties;
import ai.people.netmon.gateway.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Order(-1)
@Component
@Slf4j
public class AuthorFilter implements GlobalFilter {

    @Autowired
    private AuthService authService;

    @Autowired
    private GatewayProperties gatewayProperties;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (gatewayProperties.getWhiteList().contains(path)) {
            return chain.filter(exchange);
        }

        //取cookie中的身份令牌
        String cookieToken = authService.getTokenFromCookie(request);
        String jwtFromHeader = authService.getJwtFromHeader(request);
        if (StringUtils.isBlank(cookieToken) && StringUtils.isBlank(jwtFromHeader)) {
            log.warn("缺失Token令牌:{}", exchange.getRequest().getPath());
            throw new AuthException(AuthExceptionEnum.INVALID_TOKEN);
        }

        return chain.filter(exchange);
    }


}
